/**
 * 简洁版主逻辑 - 只包含核心记账功能
 */

// 全局变量
let currentBookId = null;
let allBooks = [];
let selectedIcon = '💰';
let selectedColor = '#4285f4';

// 数据缓存（避免频繁请求）
let cachedRecords = null;
let cachedStats = null;
let lastLoadTime = null;

// 收入和支出分类
const incomeCategories = {
  salary: '工资',
  bonus: '奖金',
  investment: '投资',
  gift: '礼金',
  other: '其他'
};

const expenseCategories = {
  food: '餐饮',
  transport: '交通',
  shopping: '购物',
  entertainment: '娱乐',
  healthcare: '医疗',
  education: '教育',
  housing: '住房',
  utilities: '水电',
  other: '其他'
};

// 账本图标和颜色
const icons = ['💰', '🏠', '✈️', '💍', '📊', '🎉', '🎓', '🚗'];
const colors = ['#4285f4', '#34a853', '#fbbc04', '#ea4335', '#9c27b0', '#00bcd4'];

// 页面加载
document.addEventListener('DOMContentLoaded', () => {
  if (!checkAuth()) return;
  
  initializeUI();
  loadBooks();
  setupEventListeners();
});

// 检查认证
function checkAuth() {
  const token = localStorage.getItem('token');
  const username = localStorage.getItem('username');
  
  if (!token || !username) {
    window.location.href = './login.html';
    return false;
  }
  
  document.getElementById('userName').textContent = username;
  return true;
}

// 初始化UI
function initializeUI() {
  const today = new Date().toISOString().split('T')[0];
  document.getElementById('recordDate').value = today;
}

// 设置事件监听
function setupEventListeners() {
  document.getElementById('recordType').addEventListener('change', (e) => {
    updateCategoryOptions(e.target.value);
  });
  
  document.getElementById('recordForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await addRecord();
  });
}

// 更新分类选项
function updateCategoryOptions(type) {
  const categorySelect = document.getElementById('recordCategory');
  categorySelect.innerHTML = '<option value="">请选择分类</option>';
  
  const categories = type === 'income' ? incomeCategories : expenseCategories;
  
  Object.entries(categories).forEach(([value, label]) => {
    const option = document.createElement('option');
    option.value = value;
    option.textContent = label;
    categorySelect.appendChild(option);
  });
}

// 加载账本列表
async function loadBooks() {
  try {
    const result = await api.books.list();
    allBooks = result.data;
    
    const grid = document.getElementById('booksGrid');
    grid.innerHTML = `
      <div class="book-card add-book-card" onclick="alert('创建账本功能开发中...')">
        <div>+</div>
        <div style="font-size: 14px;">创建账本</div>
      </div>
    `;
    
    allBooks.forEach(book => {
      const card = createBookCard(book);
      grid.appendChild(card);
    });
    
    if (allBooks.length > 0 && !currentBookId) {
      selectBook(allBooks[0].book_id);
    }
  } catch (error) {
    showToast('加载账本失败：' + error.message, 'error');
  }
}

// 创建账本卡片
function createBookCard(book) {
  const card = document.createElement('div');
  card.className = 'book-card';
  card.style.borderLeftColor = book.color || '#4285f4';
  if (book.book_id === currentBookId) {
    card.classList.add('active');
  }
  
  card.innerHTML = `
    <div style="font-size: 32px; margin-bottom: 10px;">${book.icon || '💰'}</div>
    <div style="font-weight: bold; margin-bottom: 5px;">${book.book_name}</div>
    <div style="font-size: 12px; color: #666;">${getBookTypeLabel(book.book_type)}</div>
  `;
  
  card.onclick = () => selectBook(book.book_id);
  return card;
}

// 获取账本类型标签
function getBookTypeLabel(type) {
  const labels = {
    personal: '个人账本',
    family: '家庭账本',
    travel: '旅游账本',
    wedding: '婚礼账本',
    project: '项目账本'
  };
  return labels[type] || '账本';
}

// 选择账本
async function selectBook(bookId) {
  currentBookId = bookId;
  
  document.querySelectorAll('.book-card').forEach(card => {
    card.classList.remove('active');
  });
  
  const selectedCard = Array.from(document.querySelectorAll('.book-card')).find(card => {
    return card.textContent.includes(allBooks.find(b => b.book_id === bookId)?.book_name || '');
  });
  if (selectedCard) {
    selectedCard.classList.add('active');
  }
  
  await loadRecords();
  await loadStats();
  
  document.getElementById('bookActions').style.display = 'flex';
}

// 添加记录
async function addRecord() {
  if (!currentBookId) {
    showToast('请先选择一个账本', 'warning');
    return;
  }
  
  const type = document.getElementById('recordType').value;
  const amount = parseFloat(document.getElementById('recordAmount').value);
  const category = document.getElementById('recordCategory').value;
  const date = document.getElementById('recordDate').value;
  const remark = document.getElementById('recordRemark').value;
  
  try {
    showLoading('正在添加记录...');
    await api.records.add({
      book_id: currentBookId,
      type,
      amount,
      category,
      date,
      remark
    });
    hideLoading();
    
    showSuccessAnimation('记录添加成功！');
    
    document.getElementById('recordForm').reset();
    document.getElementById('recordDate').value = new Date().toISOString().split('T')[0];
    
    await loadRecords();
    await loadStats();
  } catch (error) {
    hideLoading();
    showToast('添加失败：' + error.message, 'error');
  }
}

// 加载记录列表
async function loadRecords() {
  if (!currentBookId) return;
  
  try {
    const result = await api.records.list({ book_id: currentBookId });
    const records = result.data.records;
    
    const container = document.getElementById('recordsList');
    
    if (records.length === 0) {
      container.innerHTML = '<div class="empty-state">暂无记录，快来添加第一条吧！</div>';
      return;
    }
    
    container.innerHTML = records.map(record => `
      <div class="record-item">
        <div class="record-info">
          <div style="font-weight: bold;">${getCategoryLabel(record.category, record.type)}</div>
          <div style="font-size: 12px; color: #666;">${record.date} ${record.remark ? '· ' + record.remark : ''}</div>
        </div>
        <div class="record-amount ${record.type}">
          ${record.type === 'income' ? '+' : '-'}¥${record.amount}
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载记录失败：', error);
  }
}

// 获取分类标签
function getCategoryLabel(category, type) {
  const categories = type === 'income' ? incomeCategories : expenseCategories;
  return categories[category] || category;
}

// 加载统计数据
async function loadStats() {
  if (!currentBookId) return;
  
  try {
    const result = await api.stats.getOverview({ book_id: currentBookId });
    const stats = result.data;
    
    document.getElementById('totalIncome').textContent = '¥' + (stats.total_income || 0);
    document.getElementById('totalExpense').textContent = '¥' + (stats.total_expense || 0);
    const balance = (stats.total_income || 0) - (stats.total_expense || 0);
    document.getElementById('totalBalance').textContent = '¥' + balance.toFixed(2);
    document.getElementById('totalBalance').style.color = balance >= 0 ? '#34a853' : '#ea4335';
    
    // 分类统计
    const categoryContainer = document.getElementById('categoryStats');
    if (stats.by_category && stats.by_category.length > 0) {
      categoryContainer.innerHTML = '<div style="margin-top: 15px; font-weight: bold; margin-bottom: 10px;">支出分类</div>' +
        stats.by_category.map(cat => `
          <div style="margin-bottom: 8px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
              <span>${getCategoryLabel(cat.category, 'expense')}</span>
              <span>¥${cat.amount || 0}</span>
            </div>
            <div style="background: #eee; height: 8px; border-radius: 4px; overflow: hidden;">
              <div style="background: #4285f4; height: 100%; width: ${((cat.amount || 0) / stats.total_expense * 100)}%;"></div>
            </div>
          </div>
        `).join('');
    } else {
      categoryContainer.innerHTML = '<div style="color: #999; text-align: center; margin-top: 15px;">暂无分类统计</div>';
    }
  } catch (error) {
    console.error('加载统计失败：', error);
  }
}

// 模态框管理（简化版）
function showCreateBookModal() {
  showToast('创建账本功能请使用创新版', 'info');
}

function showPINModal() {
  showToast('PIN设置功能请使用创新版', 'info');
}

function showShareModal() {
  showToast('分享功能请使用创新版', 'info');
}

function showJoinModal() {
  showToast('加入账本功能请使用创新版', 'info');
}

function showMembersModal() {
  showToast('成员管理功能请使用创新版', 'info');
}

// 退出登录
function logout() {
  if (confirm('确定要退出登录吗？')) {
    // 清除所有登录相关数据
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('user_info');
    localStorage.removeItem('preferredVersion');
    localStorage.removeItem('currentBookId');
    
    // 清除会话存储
    sessionStorage.clear();
    
    // 跳转到登录页
    window.location.href = './login.html';
  }
}

console.log('📱 简洁版页面已加载'); 